package org.raymond.iworks.study.mq.rabbitmq.classic.hello;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.DefaultExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class Send {
    public final static String QUEUE_NAME = "hello";
    public static void main(String[] args) throws Exception {
        String message = "hello world";
        try(Connection conn = connection();
            Channel channel = conn.createChannel()){

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            log.info("[x] sent: {}", message);
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection connection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        factory.setUsername("cloud");
        factory.setPassword("cloud123");
        factory.setVirtualHost("/cloud");

        factory.setExceptionHandler(new DefaultExceptionHandler(){
            @Override
            public void handleConsumerException(Channel channel, Throwable exception, Consumer consumer, String consumerTag, String methodName) {
                super.handleConsumerException(channel, exception, consumer, consumerTag, methodName);
                log.info("consumer exception: {}", exception.getMessage());
            }
        });
        return factory.newConnection();
    }
}
